package model

import (
	"errors"
	"gorm.io/gorm"
	"saleforce/sf-backend-user/constant"
	"time"
)

type User struct {
	Id       string    `gorm:"primary_key;column:id;type:varchar(255)" json:"id"`
	Username string    `gorm:"column:username;type:varchar(255)" json:"username"`
	Nickname string    `gorm:"column:nickname;type:varchar(255)" json:"nickname"`
	Password string    `gorm:"column:password;type:varchar(255)" json:"password"`
	UserType int32     `gorm:"column:user_type;type:tinyint" json:"user_type"`
	Status   int32     `gorm:"column:status;type:tinyint" json:"status"`
	Created  time.Time `gorm:"column:created;type:timestamp" json:"created"`
	Updated  time.Time `gorm:"column:updated;type:timestamp" json:"updated"`
	IsDel    int32     `gorm:"column:is_del;type:tinyint" json:"is_del"`
	RoleId   string    `gorm:"column:role_id;type:varchar(255)" json:"role_id"`
}

// GetByUserName 用户名查询
func (u User) GetByUserName(username string) (*User, error) {
	tx := constant.Db.Model(&User{}).Omit("is_del").Where("username = ? and is_del = ?", username, 0).First(&u)
	if tx.Error != nil {
		if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
			return nil, nil
		} else {
			return nil, errors.New("Query error")
		}
	}
	return &u, nil
}

// GetById 通过ID获取用户
func (u User) GetById(id string) (*User, error) {
	tx := constant.Db.Model(&User{}).Omit("is_del").Where("id = ? and is_del = ?", id, 0).First(&u)
	if tx.Error != nil {
		if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
			return nil, nil
		} else {
			return nil, errors.New("Query error")
		}
	}
	return &u, nil
}

func (User) TableName() string {
	return "sf-user"
}
